package com.ruoyi.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.constant.CategoryTypeConstants;
import com.ruoyi.order.domain.Dish;
import com.ruoyi.order.domain.SetMeal;
import com.ruoyi.order.service.IDishService;
import com.ruoyi.order.service.ISetMealService;
import com.ruoyi.order.vo.TreeNodeVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.order.domain.Category;
import com.ruoyi.order.service.ICategoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 菜品及套餐分类Controller
 *
 * @author ruoyi
 * @date 2022-08-19
 */
@RestController
@RequestMapping("/order/category")
public class CategoryController extends BaseController
{
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IDishService dishService;
    @Autowired
    private ISetMealService setMealService;

    /**
     * 查询菜品及套餐分类列表
     */
    @PreAuthorize("@ss.hasPermi('order:category:list')")
    @GetMapping("/list")
    public TableDataInfo list(Category category)
    {
        startPage();
        List<Category> list = categoryService.selectCategoryList(category);
        return getDataTable(list);
    }

    /**
     * 导出菜品及套餐分类列表
     */
    @PreAuthorize("@ss.hasPermi('order:category:export')")
    @Log(title = "菜品及套餐分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Category category)
    {
        List<Category> list = categoryService.selectCategoryList(category);
        ExcelUtil<Category> util = new ExcelUtil<Category>(Category.class);
        util.exportExcel(response, list, "菜品及套餐分类数据");
    }

    /**
     * 获取菜品及套餐分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:category:query')")
    @GetMapping(value = "/{categoryId}")
    public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
    {
        return AjaxResult.success(categoryService.selectCategoryByCategoryId(categoryId));
    }

    /**
     * 新增菜品及套餐分类
     */
    @PreAuthorize("@ss.hasPermi('order:category:add')")
    @Log(title = "菜品及套餐分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Category category)
    {
        Date nowDate = DateUtils.getNowDate();
        category.setCreateTime(nowDate);
        category.setUpdateTime(nowDate);
        return toAjax(categoryService.insertCategory(category));
    }

    /**
     * 修改菜品及套餐分类
     */
    @PreAuthorize("@ss.hasPermi('order:category:edit')")
    @Log(title = "菜品及套餐分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Category category)
    {
        category.setUpdateTime(DateUtils.getNowDate());
        return toAjax(categoryService.updateCategory(category));
    }

    /**
     * 删除菜品及套餐分类
     */
    @PreAuthorize("@ss.hasPermi('order:category:remove')")
    @Log(title = "菜品及套餐分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{categoryIds}")
    public AjaxResult remove(@PathVariable Long[] categoryIds)
    {
        return toAjax(categoryService.deleteCategoryByCategoryIds(categoryIds));
    }

    @GetMapping("getAllCategories")
    public AjaxResult getAllCategories(){
        return AjaxResult.success(categoryService.selectCategoryList(null));
    }

    /**
     * el-tree/el-select
     */
    @GetMapping("categoryTree")
    public AjaxResult categoryTree(){
        // todo 确认排序是否正确,stream编程需要优化，不用collect api执行 执行函数，不用map api做轮询
        // old
//        List<Category> categoryList = categoryService.selectCategoryList(null);
//        categoryList.stream().map(category -> {
//            List<TreeNodeVo> children=new ArrayList<>();
//            if(StringUtils.equals(category.getCategoryType(), CategoryTypeConstants.DISH_TYPE)){
//                List<Dish> dishList = dishService.selectDishList(null);
//                dishList.stream().sorted((o1, o2) -> (int) (o1.getSort()-o2.getSort()))
//                        .map(dish -> {
//                            children.add(TreeNodeVo.builder().id(dish.getDishId()).label(dish.getDishName()).children(null).build());
//                            return null;
//                        }).collect(Collectors.toList());
//            }else if(StringUtils.equals(category.getCategoryType(),CategoryTypeConstants.SET_MEAL_TYPE)){
//                List<SetMeal> setMealList = setMealService.selectSetMealList(null);
//
//            }
//
//        })

        // new
        List<Category> categoryList = categoryService.selectCategoryList(null).stream().sorted((o1, o2) -> (int) (o1.getSort()-o2.getSort()))
                .collect(Collectors.toList());
        List<TreeNodeVo> rTreeNodeVoList=new ArrayList<>();
        for (Category category : categoryList) {
            TreeNodeVo treeNodeVo = TreeNodeVo.builder().id(category.getCategoryId()).label(category.getCategoryName()).build();
            if(StringUtils.equals(category.getCategoryType(),CategoryTypeConstants.DISH_TYPE)){
                List<Dish> dishList = dishService.selectDishList(Dish.builder().categoryId((Long) treeNodeVo.getId()).build());
                List<TreeNodeVo> treeNodeVoList = dishList.stream().sorted((o1, o2) -> (int) (o1.getSort() - o2.getSort()))
                        .map(dish -> TreeNodeVo.builder().id(dish.getDishId()).label(dish.getDishName()).children(null).build())
                        .collect(Collectors.toList());
                treeNodeVo.setChildren(treeNodeVoList);
            }else if(StringUtils.equals(category.getCategoryType(),CategoryTypeConstants.SET_MEAL_TYPE)){
                List<SetMeal> setMealList = setMealService.selectSetMealList(SetMeal.builder().categoryId((Long) treeNodeVo.getId()).build());
                List<TreeNodeVo> treeNodeVoList = setMealList.stream().sorted((o1, o2) -> (int) (o1.getSort() - o2.getSort()))
                        .map(setMeal -> TreeNodeVo.builder().id(setMeal.getSetMealId()).label(setMeal.getSetMealName()).children(null).build())
                        .collect(Collectors.toList());
                treeNodeVo.setChildren(treeNodeVoList);
            }
            rTreeNodeVoList.add(treeNodeVo);
        }
        return AjaxResult.success(rTreeNodeVoList);
    }

}
